package main

import (
	"awesomeProject2/src/test2020/util"
	"bytes"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"strings"
	"time"
)

func main() {

	baseUrl := "http://www.stats.gov.cn/tjsj/tjbz/tjyqhdmhcxhfdm/2019/"

	headers := ToMap("src/test2020/day0803/header.ini")

	url := baseUrl + "index.html"

	// 定义ff
	ff := func(type1 string) func(key string, value string) {
		return func(key string, value string) {
			fmt.Println(type1 + "ff,key:" + key + ",value:" + value)
		}
	}

	// 初始化时赋值，ff有效
	sr := &StatsRequest{url: url, headers: headers, ff: ff("type1")}

	// 直接赋值，ff有效
	sr.ff = ff("type3")

	// sr.addFilter(new(OutputFilter))
	sr.filter = new(OutputFilter)

	println(len(sr.headers))
	sr.removeHeader("Accept-Language")
	sr.addHeader("Request", "sRequest")
	println(len(sr.headers))

	// add函数赋值，ff有效
	sr.addFf(ff("type2"))

	rsp, err := sr.get()
	if err != nil {
		panic(err)
	} else {
		responseText := util.ToGBK2(rsp)
		// println(responseText)

		doc, err := goquery.NewDocumentFromReader(bytes.NewReader([]byte(responseText)))
		if err != nil {
			panic(err)
		}

		stats := Stats{Id: "100000000000", Name: "中国"}

		find := doc.Find("tr .provincetr td:has(a)")
		size := find.Size()
		fmt.Println(size)
		child := make([]Stats, size)
		stats.Child = child

		find.Each(func(i int, s *goquery.Selection) {
			band := s.Find("a").Text()
			href, _ := s.Find("a").Attr("href")

			prefix := handleHref(href)
			prefix = util.LeftFull(prefix, 12)
			if "" != band {
				s := Stats{Id: prefix, Name: band, Pid: stats.Id}
				fmt.Print("正在查询[" + band + "]的下级")
				// s.Child = getChildCity(baseUrl, headers, href, prefix, band)
				fmt.Println("\t查询完成")
				stats.addChild(i, s)
				time.Sleep(100 * time.Millisecond)
			} else {

			}
		})
		fmt.Println(stats.toJson())
	}
}

func getChildCity(baseUrl string, headers map[string]string, href string, pid string, pName string) []Stats {
	s := StatsRequest{url: baseUrl + href, headers: headers}
	resp, _ := s.get()
	responseText := util.ToGBK2(resp)
	doc, _ := goquery.NewDocumentFromReader(bytes.NewReader([]byte(responseText)))
	find := doc.Find("tr .citytr")
	size := find.Size()
	child := make([]Stats, size)
	find.Each(func(i int, s *goquery.Selection) {
		id := s.Find("td:nth-child(1)").Text()
		name := s.Find("td:nth-child(2)").Text()
		currentHref, _ := s.Find("a").Attr("href")
		if "" != name {
			if "市辖区" == name {
				name = pName
			}
			s := Stats{Id: id, Name: name, Pid: pid}
			fmt.Println()
			fmt.Print("正在查询[" + name + "]的下级")
			s.Child = getChildCounty(baseUrl, headers, currentHref, id, name)
			fmt.Println("\t查询完成")
			child[i] = s
			time.Sleep(100 * time.Millisecond)
		}
	})
	return child
}

func getChildCounty(baseUrl string, headers map[string]string, href string, pid string, pName string) []Stats {
	s := StatsRequest{url: baseUrl + href, headers: headers}
	resp, _ := s.get()
	responseText := util.ToGBK2(resp)
	doc, _ := goquery.NewDocumentFromReader(bytes.NewReader([]byte(responseText)))
	find := doc.Find("tr .countytr")
	size := find.Size()
	child := make([]Stats, size)
	find.Each(func(i int, s *goquery.Selection) {
		selection := s.Has("a")
		var has bool = true
		if selection.Nodes == nil {
			has = false
		}
		id := s.Find("td:nth-child(1)").Text()
		name := s.Find("td:nth-child(2)").Text()
		if "" != name {
			if "市辖区" == name {
				name = pName
			}
			s := Stats{Id: id, Name: name, Pid: pid}
			if has {
				getC()
			}
			child[i] = s
		}
	})
	return child
}

func getC()  {

}

func handleHref(href string) string {
	if "" == href {
		return href
	}
	index := strings.Index(href, ".")
	return href[0:index]
}
